﻿using System;
using System.Collections.Generic;
using System.Linq;
using Sharp.DataTransferObject;
using Sharp.Domain.PlatformBoundedContext.OrgModule.Aggregates;
using Sharp.Domain.PlatformBoundedContext.OrgModule.Services;
using Sharp.Domain.PlatformBoundedContext.PersonModule.Aggregates;
using Sharp.Domain.PlatformBoundedContext.PersonModule.Services;
using Sharp.Domain.Repositories;
using Sharp.Infrastructure;
using Sharp.Infrastructure.Crosscutting;
using Sharp.Infrastructure.Search;
using Sharp.ServiceContracts;

namespace Sharp.Application.Platform
{

    /// <summary>
    /// 企业服务
    /// </summary>
    public class EnterpriseServiceImp : ApplicationService, IEnterpriseService
    {
        #region 私有字段

        private readonly IPersonService _personService;
        private readonly IOrgService _orgService;

        private readonly IEmployeeRepository _employeeRepository;
        private readonly IGroupRepository _groupRepository;
        private readonly IJobRepository _jobRepository;

        private readonly IOrgRepository _orgRepository;
        private readonly IOrgLevelRepository _orgLevelRepository;
        private readonly IOrgForBusinessRepository _orgForBusinessRepository;
        private readonly IOrgForBusinessListRepository _orgForBusinessListRepository;


        #endregion

        #region 构造函数

        /// <summary>
        /// 初始化
        /// </summary>
        /// <param name="context"></param>
        /// <param name="employeeRepository"></param>
        /// <param name="groupRepository"></param>
        /// <param name="jobRepository"></param>
        /// <param name="orgRepository"></param>
        /// <param name="orgLevelRepository"></param>
        /// <param name="orgForBusinessRepository"></param>
        /// <param name="orgForBusinessListRepository"></param>
        /// <param name="personService"></param>
        /// <param name="orgService"></param>
        public EnterpriseServiceImp(IRepositoryContext context,
            IEmployeeRepository employeeRepository,
            IGroupRepository groupRepository,
            IJobRepository jobRepository,

            IOrgRepository orgRepository,
            IOrgLevelRepository orgLevelRepository,
            IOrgForBusinessRepository orgForBusinessRepository,
            IOrgForBusinessListRepository orgForBusinessListRepository,


            IPersonService personService,
            IOrgService orgService
            )
            : base(context)
        {

            _employeeRepository = employeeRepository;
            _groupRepository = groupRepository;
            _jobRepository = jobRepository;

            _orgRepository = orgRepository;
            _orgLevelRepository = orgLevelRepository;
            _orgForBusinessRepository = orgForBusinessRepository;
            _orgForBusinessListRepository = orgForBusinessListRepository;


            _personService = personService;
            _orgService = orgService;
        }

        #endregion

        #region 雇员
        #region 保存雇员
        /// <summary>
        /// 保存雇员
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        [Logging("保存员工“{@p0.FullName}”")]
        public Result SaveEmployee(EmployeeDTO model)
        {
            Result res = new Result();
            var info = model.To<Employee>();
            if (info.Id.IsEmpty())
            {
                _employeeRepository.Add(info);
            }
            else
            {
                _employeeRepository.Update(info);
            }
            Context.Commit();
            return res;
        }
        #endregion

        #region 删除员工
        /// <summary>
        /// 删除员工
        /// </summary>
        /// <param name="ids"></param>
        /// <returns></returns>
        [Logging("删除员工“{@p0}”")]
        public Result DeleteEmployee(Guid[] ids)
        {
            var res = new Result();
            if (ids == null)
            {
                res.Err = "Id参数不可为空！";
                return res;
            }

            res = _personService.DeleteEmployee(ids);
            return res;
        }
        #endregion

        #region 获取一条主数据
        /// <summary>
        /// 获取一条主数据
        /// </summary>
        /// <returns></returns>
        public EmployeeDTO GetEmployeeInfo(Guid id)
        {
            return _employeeRepository.Get(id).To<EmployeeDTO>();
        }
        #endregion

        #region 获取分页数据

        /// <summary>
        /// 获取分页数据
        /// </summary>
        /// <param name="pf"></param>
        /// <returns></returns>
        public PagedResult<EmployeeDTO> GetEmployeePaged(PagingFeature pf)
        {
            var paged = _employeeRepository.Pagging(pf, null,
                x => x.Job);

            var output = paged.To<Employee, EmployeeDTO>();

            output.Data.ForEach(x =>
            {
                if (x.Birthday.IsNullOrEmpty() || x.Birthday.Length < 4)
                {
                    return;
                }
                int age;
                if (int.TryParse(x.Birthday.Substring(0, 4), out age))
                {
                    x.Age = DateTime.Now.Year - age;
                }
            });
            return output;
        }
        #endregion

        #region 组织里面的员工
        /// <summary>
        /// 组织里面的员工
        /// </summary>
        /// <param name="orgIds"></param>
        /// <returns></returns>
        public IEnumerable<EmployeeDTO> GetEmployeesInOrg(Guid[] orgIds)
        {
            if (orgIds == null)
            {
                return new List<EmployeeDTO>();
            }

            var list = _employeeRepository.GetList(x => orgIds.Contains(x.OrgId.Value)).To<Employee, EmployeeDTO>();

            return list;
        }
        #endregion

        #endregion


        #region 组织结构
        [CacheRemove("GetOrgs"), Logging("保存组织结构“{@p0.Title}”")]
        public Result SaveOrg(OrgDTO model)
        {
            Result res = new Result();
            var info = model.To<Org>();
            if (info.Id.IsEmpty())
            {
                _orgRepository.Add(info);
            }
            else
            {
                _orgRepository.Update(info);
            }
            Context.Commit();
            return res;
        }

        [Logging("删除组织结构“{@p0}”"), CacheRemove("GetOrgs")]
        public Result DeleteOrgs(Guid[] ids)
        {
            var res = new Result();
            if (ids == null)
            {
                res.Err = "Id参数不可为空！";
                return res;
            }

            this._orgRepository.Remove(ids);

            this.Context.Commit();
            return res;
        }

        public OrgDTO GetOrgInfo(Guid id)
        {
            var info = _orgRepository.Get(id);

            return info.To<OrgDTO>();
        }
        /// <summary>
        /// 获取所有组织结构
        /// </summary>
        /// <returns></returns>
        [Cache("GetOrgs")]
        public IEnumerable<OrgDTO> GetOrgs()
        {
            return _orgRepository.GetList().To<Org, OrgDTO>();
        }
        /// <summary>
        /// 组织结构排序
        /// </summary>
        /// <param name="parentId"></param>
        /// <param name="ids"></param>
        /// <returns></returns>
        [CacheRemove("GetOrgs")]
        public Result OrgMoveOrSort(Guid? parentId, Guid[] ids)
        {
            Result res = _orgService.MoveOrSort(parentId, ids);


            return res;
        }
        /// <summary>
        /// 获取组织结构层次
        /// </summary>
        /// <returns></returns>
        public IEnumerable<OrgLevelDTO> GetOrgLevelList()
        {
            return _orgLevelRepository.GetList().To<OrgLevel, OrgLevelDTO>();
        }

        [Logging("保存组“{@p0.Title}”")]
        public Result SaveGroup(GroupDTO model)
        {
            Result res = new Result();

            if (model.Id.IsEmpty())
            {
                var info = model.To<Group>();
                _groupRepository.Add(info);
            }
            else
            {
                var info = _groupRepository.Get(model.Id);
                info.Code = model.Code;
                info.OrgId = model.OrgId;
                info.Remark = model.Remark;
                info.Title = model.Title;

                _groupRepository.Update(info);
            }
            Context.Commit();
            return res;
        }

        [Logging("删除组“{@p0}”")]
        public Result DeleteGroups(Guid[] ids)
        {
            var res = new Result();
            if (ids == null)
            {
                res.Err = "Id参数不可为空！";
                return res;
            }

            this._groupRepository.Remove(ids);

            this.Context.Commit();
            return res;
        }

        public GroupDTO GetGroupInfo(Guid id)
        {
            var info = _groupRepository.Get(id, x => x.Org);
            var dto = info.To<GroupDTO>();
            if (info.Org != null)
                dto.OrgTitle = info.Org.Title;
            return dto;
        }

        public PagedResult<GroupDTO> GetGroupPaged(PagingFeature pf)
        {
            var paged = _groupRepository.Pagging(pf);

            var dto = paged.To<Group, GroupDTO>();
            foreach (var item in dto.Data)
            {
                item.MemberCount = _employeeRepository.Count(x => x.Groups.Any(y => y.Id == item.Id));
            }

            return dto;
        }
        #endregion

        #region 工作岗位
        #region 保存工作岗位
        /// <summary>
        /// 保存工作岗位
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        [Logging("保存工作岗位“{@p0.Title}”")]
        public Result SaveJob(JobDTO model)
        {
            Result res = new Result();
            var info = model.To<Job>();
            if (info.Id.IsEmpty())
            {
                _jobRepository.Add(info);
            }
            else
            {
                _jobRepository.Update(info);
            }
            Context.Commit();
            return res;
        }
        #endregion

        #region 删除岗位
        /// <summary>
        /// 删除岗位
        /// </summary>
        /// <param name="ids"></param>
        /// <returns></returns>
        [Logging("删除工作岗位“{@p0}”")]
        public Result DeleteJob(Guid[] ids)
        {
            var res = new Result();
            if (ids == null)
            {
                res.Err = "Id参数不可为空！";
                return res;
            }

            res = _personService.DeleteJob(ids);
            return res;
        }
        #endregion

        #region 获取一条主数据
        /// <summary>
        /// 获取一条主数据
        /// </summary>
        /// <returns></returns>
        public JobDTO GetJobInfo(Guid id)
        {
            return _jobRepository.Get(id).To<JobDTO>();
        }
        #endregion

        #region 获取分页数据

        /// <summary>
        /// 获取分页数据
        /// </summary>
        /// <param name="pf"></param>
        /// <returns></returns>
        public PagedResult<JobDTO> GetJobPaged(PagingFeature pf)
        {
            var paged = _jobRepository.Pagging(pf);

            var output = paged.To<Job, JobDTO>();


            return output;
        }
        #endregion

        #endregion


   
    }
}
